<?php

class Mysql
{
	private $host = 'localhost';
	private $user = 'root';
	private $pass = '';
	private $base;
	private $query;
	private $result_id;
	private $connect_id = 0;
	static protected $instance;

	// Constructeur initialise les parametre de la connexion
	function __construct($Host='localhost', $User='root', $Pass='', $Base)
	{
		$this->host=$Host;
		$this->user=$User;
		$this->pass=$Pass;
		$this->base=$Base;
	}

	static function get()
	{
		if(!self::$instance)
			self::$instance = new self(Settings::$dbHost,Settings::$dbLogin,Settings::$dbPwd,Settings::$dbName);

		return self::$instance;
	}

	// connection à la DB
	private function connect($Host, $User, $Pass, $Base)
	{
		if ($this->connect_id = mysql_connect($Host, $User, $Pass))
		{
			if(mysql_select_db($Base, $this->connect_id))
				return $this->connect_id;
			else
			{
				trigger_error('Impossible de sélectionner une base de données',E_USER_ERROR);
				return false;
			}
		}
		else
		{
			trigger_error('Impossible de se connecter à la base de données',E_USER_ERROR);
			return false;
		}
	}

	// Envoi d'une requete a la DB
	function query($query)
	{
		if ( !$this->connect_id ) $this->connect($this->host,$this->user,$this->pass,$this->base);
		if ( $this->result_id = mysql_query($query, $this->connect_id) )
		{
			$this->query = trim($query);
			return $this->result_id;
		}
		else
		{
			trigger_error(mysql_error(),E_USER_ERROR);
			return false;
		}
	}

	// return the last auto increment insert ID, only use on MySQL
	function last_insert_id()
	{
		return mysql_insert_id();
	}

	// renvoi le nombre d'enregistrement affecté
	function num_rows()
	{
		if ( isset($this->result_id) )
		{
			if ( preg_match('`^select`i',$this->query) ) return mysql_num_rows($this->result_id);
			if ( preg_match('`^(update|delete)`i',$this->query) ) return mysql_affected_rows();
			if ( preg_match('`^insert`i',$this->query) ) return $this->result_id;
		}
		else
		{
			trigger_error('Resource non spécifiée',E_USER_WARNING);
			return false;
		}
	}

	function get_object($query)
	{
		return @mysql_fetch_object($query);
	}

	function get_array($query, $mode='')
	{
		switch($mode)
		{
			case 'NUMERIC' :
			return @mysql_fetch_array($query, MYSQL_NUM);
			break;
			case 'BOTH' :
			return @mysql_fetch_array($query, MYSQL_BOTH);
			break;
			default :
			return @mysql_fetch_assoc($query);
		}
	}

	// ferme la connection
	function close()
	{
		return mysql_close($this->connect_id) ;
	}

	// vide les resultat des requete
	function free_result()
	{
		return @mysql_free_result($this->connect_id);
	}
}
?>
